﻿Imports ProgettoSicurezza.Client.CAServices
Imports System.IO
Imports System.Xml.Serialization
Imports Ionic.Zip
Imports Org.BouncyCastle.Crypto.Parameters
Imports System.ComponentModel
Imports Org.BouncyCastle.Security
Imports SharedTools
Imports System.Collections.ObjectModel
Imports System.Threading
Imports System.ServiceModel
Imports System.ServiceModel.Discovery
Imports System.ServiceModel.Description
Imports ProgettoSicurezza.Client.ClientServices

Class MainWindow
    Implements INotifyPropertyChanged


    Private Property Timer As Timers.Timer
    Private ReadOnly Property Profile As ClientProfile
        Get
            Return Repository.CurrentProfile
        End Get
    End Property

#Region "Presentation Helper Properties"
    Public ReadOnly Property ButtonSigCertRequestVisibility As Visibility
        Get
            If Profile IsNot Nothing AndAlso Not Profile.WaitingForSigCert AndAlso (Profile.SigCert Is Nothing OrElse Profile.SigCert.Certificate Is Nothing) Then
                Return Windows.Visibility.Visible
            Else
                Return Windows.Visibility.Collapsed
            End If
        End Get
    End Property

    Public ReadOnly Property ButtonSigCertCheckVisibility As Visibility
        Get
            If Profile IsNot Nothing AndAlso Profile.WaitingForSigCert Then
                Return Windows.Visibility.Visible
            Else
                Return Windows.Visibility.Collapsed
            End If
        End Get
    End Property

    Public ReadOnly Property ButtonCryptoCertRequestVisibility As Visibility
        Get
            If Profile IsNot Nothing AndAlso Not Profile.WaitingForCryptoCert AndAlso (Profile.CryptoCert Is Nothing OrElse Profile.CryptoCert.Certificate Is Nothing) AndAlso Profile.SigCert IsNot Nothing AndAlso Profile.SigCert.Certificate IsNot Nothing AndAlso Not Profile.WaitingForSigCert Then
                Return Windows.Visibility.Visible
            Else
                Return Windows.Visibility.Collapsed
            End If
        End Get
    End Property

    Public ReadOnly Property ButtonCryptoCertCheckVisibility As Visibility
        Get
            If Profile IsNot Nothing AndAlso Profile.WaitingForCryptoCert Then
                Return Windows.Visibility.Visible
            Else
                Return Windows.Visibility.Collapsed
            End If
        End Get
    End Property

    Public ReadOnly Property IsCRLReady As Boolean
        Get
            Return Profile IsNot Nothing AndAlso Profile.LocalCRL IsNot Nothing
        End Get
    End Property

    Public ReadOnly Property CanSign As Boolean
        Get
            Return Profile IsNot Nothing AndAlso Profile.SigCert IsNot Nothing AndAlso Profile.SigCert.Certificate IsNot Nothing AndAlso Profile.SigCert.Certificate.NotAfter > DateTime.Now
        End Get
    End Property
#End Region


    Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        My.Application.CAMessageService = New MessagesServiceClient("NetTcpBinding_IMessagesService")


        Client2ClientHelper.CreateAndStartClientMessageService()

        While Not CertificatesManager.LoadCACertificate()
            Dim result = MessageBox.Show(Me, "The CA public certificate was either not found or expired. Please run the CA application first and generate a certificate for the CA, then retry" & vbCrLf & vbCrLf & "Retry to load the CA certificate?", "CA certificate problem", MessageBoxButton.YesNo, MessageBoxImage.Warning)
            If result = MessageBoxResult.No Then
                Me.Close()
                Return
            End If
        End While

        Dim appdata = FileSystemUtilities.AppPath

        FileSystemUtilities.CheckAndCreateDirectories()

        Dim userfiles = Directory.GetFiles(appdata & "\ProgettoSicurezza\users", "*.zip")
        Dim users = (From u In userfiles Select u.Substring(u.LastIndexOf("\") + 1, u.Length - u.LastIndexOf("\") - 5)).ToArray

        If userfiles.Count = 0 Then
            'Crea nuovo profilo utente
            Dim initialized = InitializeProfile(users)
            If Not initialized Then
                Me.Close()
                Return
            End If
        Else
            'Carica profilo utente
            Dim badPass As Boolean = False

            'testa pass
            While Repository.CurrentProfile Is Nothing
                Dim pf As New PasswordForm(badPass, users)
                Dim res = PresentationUtilities.ShowControlAsDialogWindow(pf, "Unlock profile", Windows.WindowStyle.ToolWindow)

                If Not res.HasValue OrElse res.Value = False Then
                    If pf.CreateProfile = False Then
                        Me.Close() 'Dialog was canceled, close application
                        Return
                    Else
                        'Nuovo profilo
                        Dim initialized = InitializeProfile(users)
                        If Not initialized Then
                            Me.Close()
                            Return
                        End If
                        Exit While
                    End If
                End If
                badPass = Not ProfileManager.LoadProfile(pf.User, pf.Password)
            End While
        End If

        ReloadUI()

        Timer = New Timers.Timer
        Timer.AutoReset = True
        Timer.Interval = 5000
        AddHandler Timer.Elapsed, AddressOf TimerElapsed
        Timer.Start()
    End Sub




    Public Function InitializeProfile(users As IEnumerable(Of String)) As Boolean
        Dim nf As New NewProfileForm(users)
        Dim result = PresentationUtilities.ShowControlAsDialogWindow(nf, "Creating new user profile...")
        If result.HasValue AndAlso result.Value = True Then
            ProfileManager.CreateNewProfile(nf)
            ReloadUI()
            Return True
        End If
        Return False
    End Function

    Private Sub ReloadUI()
        LoadCertsTab()
        LoadCRLTab()
        LoadPDFTab()

        tbLogged.Inlines.Clear()
        tbLogged.Inlines.Add(New Run("Logged in as: "))
        tbLogged.Inlines.Add(New Bold(New Run(Repository.CurrentProfile.UserName)))

    End Sub

    Private Sub LoadCertsTab()
        If Profile Is Nothing Then
            Return
        End If

        If Profile.SigCert Is Nothing OrElse Profile.SigCert.Certificate Is Nothing Then
            stackSigCertInfo.Visibility = Windows.Visibility.Collapsed
            If Profile.WaitingForSigCert = False Then
                tbSigCertStatus.Text = "You don't have a certificate yet. Click on the button below to contact the CA and request a digital signature certificate."
                tbSigCertStatus.Foreground = Brushes.Red
            Else
                tbSigCertStatus.Text = "You have requested a certificate for signing to the CA. When your request is accepted (if it is) you will be able to retrieve it. Click on the button below to check if your certificate is ready and retrieve it if it is."
                tbSigCertStatus.Foreground = Brushes.Chocolate
            End If
        Else
            stackSigCertInfo.Visibility = Windows.Visibility.Visible
            If Profile.SigCert.Certificate.NotAfter > DateTime.Now Then
                tbSigCertStatus.Text = "Certificate for signing ok!"
                tbSigCertStatus.Foreground = Brushes.Green
                tbSigCertExpiration.Text = "Expires on:  " & Profile.SigCert.Certificate.NotAfter.ToString()
                tbSigCertSerial.Text = "Serial number:  " & Profile.SigCert.Certificate.SerialNumber.ToString
            Else
                tbSigCertStatus.Text = "Certificate for signing is expired! You can still use the certificate, but keep in mind the CA or other clients may refuse it. Please, revoke the certificate and request a new one to restore full functionality."
                tbSigCertStatus.Foreground = Brushes.Chocolate
                tbSigCertExpiration.Text = "Expired on:  " & Profile.SigCert.Certificate.NotAfter.ToString()
                tbSigCertSerial.Text = "Serial number:  " & Profile.SigCert.Certificate.SerialNumber.ToString
            End If
        End If

        If Profile.CryptoCert Is Nothing OrElse Profile.CryptoCert.Certificate Is Nothing Then
            stackCryptoCertInfo.Visibility = Windows.Visibility.Collapsed
            If Profile.WaitingForCryptoCert = False Then
                If Profile.SigCert Is Nothing OrElse Profile.WaitingForSigCert Then
                    tbCryptoCertStatus.Text = "You don't have a certificate for cryptography yet. To request one, you first need a certificate for the digital signature. Use the panel above to request one."
                    tbCryptoCertStatus.Foreground = Brushes.Red
                Else
                    tbCryptoCertStatus.Text = "You don't have a certificate for cryptography yet. Click on the button below to contact the CA and request a cryptography certificate."
                    tbCryptoCertStatus.Foreground = Brushes.Red
                End If
            Else
                tbCryptoCertStatus.Text = "You have requested a certificate for cyptography to the CA. When your request is accepted (if it is) you will be able to retrieve it. Click on the button below to check if your certificate is ready and retrieve it if it is."
                tbCryptoCertStatus.Foreground = Brushes.Chocolate
            End If
        Else
            stackCryptoCertInfo.Visibility = Windows.Visibility.Visible
            If Profile.CryptoCert.Certificate.NotAfter > DateTime.Now Then
                tbCryptoCertStatus.Text = "Certificate for cryptography ok!"
                tbCryptoCertStatus.Foreground = Brushes.Green
                tbCryptoCertExpiration.Text = "Expires on:  " & Profile.CryptoCert.Certificate.NotAfter.ToString()
                tbCryptoCertSerial.Text = "Serial number:  " & Profile.CryptoCert.Certificate.SerialNumber.ToString
            Else
                tbCryptoCertStatus.Text = "Certificate for cryptography is expired! You can still use the certificate, but keep in mind the CA or other clients may refuse it. Please, revoke the certificate and request a new one to restore full functionality."
                tbCryptoCertStatus.Foreground = Brushes.Chocolate
                tbCryptoCertExpiration.Text = "Expired on:  " & Profile.CryptoCert.Certificate.NotAfter.ToString()
                tbCryptoCertSerial.Text = "Serial number:  " & Profile.CryptoCert.Certificate.SerialNumber.ToString
            End If
        End If


        OnPropertyChanged("ButtonCryptoCertRequestVisibility")
        OnPropertyChanged("ButtonCryptoCertCheckVisibility")
        OnPropertyChanged("ButtonSigCertRequestVisibility")
        OnPropertyChanged("ButtonSigCertCheckVisibility")
        OnPropertyChanged("CanSign")
    End Sub

    Private Sub LoadCRLTab()
        If Repository.CurrentProfile IsNot Nothing AndAlso Repository.CurrentProfile.LocalCRL IsNot Nothing Then
            If Repository.CurrentProfile.LocalCRL.NextUpdate.Value < DateTime.Now Then
                tbCRLStatus.Foreground = Brushes.Red
                tbCRLStatus.Text = "Expired"
                tbCRLStatus.ToolTip = "Local CRL expired on: " & Repository.CurrentProfile.LocalCRL.NextUpdate.Value.ToString
            Else
                tbCRLStatus.Foreground = Brushes.Green
                tbCRLStatus.Text = "Valid"
                tbCRLStatus.ToolTip = "Local CRL is currently valid. It will expire on: " & Repository.CurrentProfile.LocalCRL.NextUpdate.Value.ToString
            End If
        Else
            tbCRLStatus.Foreground = Brushes.Black
            tbCRLStatus.Text = "Not downloaded yet"
            tbCRLStatus.ToolTip = "You have yet to download a CRL. Click on the button on the right to download a CRL now from the CA"
        End If

        If Profile IsNot Nothing Then
            If Profile.OldCertificates Is Nothing Then
                Profile.OldCertificates = New ObservableCollection(Of CertificateItem)
            End If
            If dg.ItemsSource Is Nothing Then
                dg.ItemsSource = Profile.OldCertificates
            End If
        End If

        OnPropertyChanged("IsCRLReady")
        OnPropertyChanged("CanSign")
    End Sub

    Private Sub LoadPDFTab()
        If Repository.PDFDocuments Is Nothing Then
            Repository.PDFDocuments = New ObservableCollection(Of PDFItem)
        End If

        If tabPdf.Content Is Nothing Then
            tabPdf.Content = New PDFControl
        End If
        DirectCast(tabPdf.Content, PDFControl).CertificatesUpdated()
    End Sub

    Private Sub buttonSigCertRequest_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim resul = CertificatesManager.SendCertificateRequest(SharedTools.CertificateType.Signature)

        Select Case resul
            Case CertificateRequestResponse.CommunicationFailed
                PresentationUtilities.ShowStandardMessage(StandardMessages.CommunicationFailed)
            Case CertificateRequestResponse.Accepted
                ReloadUI()
            Case CertificateRequestResponse.CertificateAlreadyRequested
                ReloadUI()
            Case CertificateRequestResponse.SignatureVerificationFailed
                PresentationUtilities.ShowStandardMessage(StandardMessages.ClientSignatureInvalid)
        End Select
    End Sub


    Private Sub buttonCryptoCertRequest_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim resul = CertificatesManager.SendCertificateRequest(SharedTools.CertificateType.Cryptography)

        Select Case resul
            Case CertificateRequestResponse.CommunicationFailed
                PresentationUtilities.ShowStandardMessage(StandardMessages.CommunicationFailed)
            Case CertificateRequestResponse.Accepted
                ReloadUI()
            Case CertificateRequestResponse.CertificateAlreadyRequested
                ReloadUI()
            Case CertificateRequestResponse.SignatureVerificationFailed
                PresentationUtilities.ShowStandardMessage(StandardMessages.ClientSignatureInvalid)
        End Select
    End Sub

    Private Sub buttonSigCertCheck_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Select Case CertificatesManager.CheckIfCertificateReady(SharedTools.CertificateType.Signature)
            Case SharedTools.CertificateRequestStatus.Accepted
                ReloadUI()
            Case SharedTools.CertificateRequestStatus.Refused
                MessageBox.Show(Me, "The CA administrator refused your request for a certificate. Please contact the CA administrator for further inquiry.", "Request refuse", MessageBoxButton.OK, MessageBoxImage.Warning)
                ReloadUI()
            Case SharedTools.CertificateRequestStatus.Pending
                MessageBox.Show(Me, "Your certificate is not ready yet. Please try again in a while." & vbCrLf & vbCrLf & "Remember the CA administrator must confirm your certificate manually before you can download it.", "Not Ready", MessageBoxButton.OK, MessageBoxImage.Information)
            Case SharedTools.CertificateRequestStatus.SignatureException
                PresentationUtilities.ShowStandardMessage(StandardMessages.ClientSignatureInvalid)
        End Select
    End Sub

    Private Sub buttonCryptoCertCheck_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Select Case CertificatesManager.CheckIfCertificateReady(SharedTools.CertificateType.Cryptography)
            Case SharedTools.CertificateRequestStatus.Accepted
                ReloadUI()
            Case SharedTools.CertificateRequestStatus.Refused
                MessageBox.Show(Me, "The CA administrator refused your request for a certificate. Please contact the CA administrator for further inquiry.", "Request refuse", MessageBoxButton.OK, MessageBoxImage.Warning)
                ReloadUI()
            Case SharedTools.CertificateRequestStatus.Pending
                MessageBox.Show(Me, "Your certificate is not ready yet. Please try again in a while." & vbCrLf & vbCrLf & "Remember the CA administrator must confirm your certificate manually before you can download it.", "Not Ready", MessageBoxButton.OK, MessageBoxImage.Information)
            Case SharedTools.CertificateRequestStatus.SignatureException
                MessageBox.Show(Me, "Error! The CA reports that the signature verification failed! Something went horribly wrong :(", "Signature invalid", MessageBoxButton.OK, MessageBoxImage.Error)
        End Select
    End Sub

    Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
    Private Overloads Sub OnPropertyChanged(name As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name))
    End Sub

#Region "Current Certificates Events"

    Private Sub ButtonSigView_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        CertificatesManager.ShowCertificateDetails(Profile.SigCert.Certificate)
    End Sub

    Private Sub ButtonSigRenew_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim res = MessageBox.Show("This will revoke your current signature certificate and automatically obtain a new one from the CA. Your personal data will be kept, but the certificate key will be regenerated." & vbCrLf & vbCrLf & "Are you sure you want to proceed?", "Confirm renewal", MessageBoxButton.YesNo, MessageBoxImage.Question)
        If res = MessageBoxResult.Yes Then
            Dim result = CertificatesManager.RenewCertificate(CertificateType.Signature, Repository.CurrentProfile)
            Select Case result
                Case GenericQueryResponse.Ok
                    MessageBox.Show("Certificates renewed succesfully!", "Success", MessageBoxButton.OK, MessageBoxImage.Information)
                    ReloadUI()
                Case GenericQueryResponse.ClientUnknownException
                    PresentationUtilities.ShowStandardMessage(StandardMessages.ClientUnknown)
                Case GenericQueryResponse.SignatureException
                    PresentationUtilities.ShowStandardMessage(StandardMessages.ClientSignatureInvalid)
            End Select
        End If
    End Sub

    Private Sub ButtonSigRevoke_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim res = MessageBox.Show("This will permanently revoke both your certificate for digital signature and your certificate for cryptography (if you have one). You will need to request both certificates again to be able to sign/encrypt anything." & vbCrLf & vbCrLf & "Are you sure?", "Confirm revocation", MessageBoxButton.YesNo, MessageBoxImage.Question)
        If res = MessageBoxResult.Yes Then
            Try
                Dim revoked = CRLManager.RevokeCertificate(SharedTools.CertificateType.Signature)
                Select Case revoked
                    Case GenericQueryResponse.Ok
                        ReloadUI()
                    Case GenericQueryResponse.ClientUnknownException
                        PresentationUtilities.ShowStandardMessage(StandardMessages.ClientUnknown)
                    Case GenericQueryResponse.SignatureException
                        PresentationUtilities.ShowStandardMessage(StandardMessages.ClientSignatureInvalid)
                End Select
            Catch ex As SignatureException
                PresentationUtilities.ShowStandardMessage(StandardMessages.CASignatureInvalid)
            End Try
        End If
    End Sub


    Private Sub ButtonCryptoView_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        CertificatesManager.ShowCertificateDetails(Profile.CryptoCert.Certificate)
    End Sub

    Private Sub ButtonCryptoRenew_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim res = MessageBox.Show("This will revoke your current signature certificate and automatically obtain a new one from the CA. Your personal data will be kept, but the certificate key will be regenerated." & vbCrLf & vbCrLf & "Are you sure you want to proceed?", "Confirm renewal", MessageBoxButton.YesNo, MessageBoxImage.Question)
        If res = MessageBoxResult.Yes Then
            Dim result = CertificatesManager.RenewCertificate(CertificateType.Cryptography, Repository.CurrentProfile)
            Select Case result
                Case GenericQueryResponse.Ok
                    MessageBox.Show("Certificate renewed succesfully!", "Success", MessageBoxButton.OK, MessageBoxImage.Information)
                    ReloadUI()
                Case GenericQueryResponse.ClientUnknownException
                    PresentationUtilities.ShowStandardMessage(StandardMessages.ClientUnknown)
                Case GenericQueryResponse.SignatureException
                    PresentationUtilities.ShowStandardMessage(StandardMessages.ClientSignatureInvalid)
            End Select
        End If
    End Sub

    Private Sub ButtonCryptoRevoke_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim res = MessageBox.Show("This will permanently revoke your certificate for cryptography. You will need to request a new one to be able to encrypt anything." & vbCrLf & vbCrLf & "Are you sure?", "Confirm revocation", MessageBoxButton.YesNo, MessageBoxImage.Question)
        If res = MessageBoxResult.Yes Then
            Try
                Dim revoked = CRLManager.RevokeCertificate(SharedTools.CertificateType.Cryptography)
                Select Case revoked
                    Case GenericQueryResponse.Ok
                        ReloadUI()
                    Case GenericQueryResponse.ClientUnknownException
                        PresentationUtilities.ShowStandardMessage(StandardMessages.ClientUnknown)
                    Case GenericQueryResponse.SignatureException
                        PresentationUtilities.ShowStandardMessage(StandardMessages.ClientSignatureInvalid)
                End Select
            Catch ex As SignatureException
                PresentationUtilities.ShowStandardMessage(StandardMessages.CASignatureInvalid)
            End Try
        End If
    End Sub

#End Region

#Region "CRL Events"
    Private Sub ButtonOldCertDetails_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        CertificatesManager.ShowCertificateDetails(DirectCast(dg.SelectedItem, CertificateItem).Certificate)
    End Sub

    Private Sub ButtonOldCertCheckCRL_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim res = CRLManager.CheckCertificateAgainstLocalCRL(DirectCast(dg.SelectedItem, CertificateItem).Certificate)
        If res Then
            MessageBox.Show("The CRL reports that the certificate is revoked!", "Result", MessageBoxButton.OK, MessageBoxImage.Information)
        Else
            MessageBox.Show("The CRL reports that the certificate is still valid! (CRL is probably outdated, try to reload it)", "Result", MessageBoxButton.OK, MessageBoxImage.Information)
        End If
    End Sub

    Private Sub ButtonOldCertCheckOCSP_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim res = CRLManager.CheckCertificateAgainstOCSP(DirectCast(dg.SelectedItem, CertificateItem).Certificate)
        Select Case res.Item1
            Case OCSPQueryResponse.Revoked
                MessageBox.Show("The OCSP server reports that the certificate is revoked!" & vbCrLf & vbCrLf & "Revocation date: " & res.Item2.ToString, "Result", MessageBoxButton.OK, MessageBoxImage.Information)
            Case OCSPQueryResponse.Valid
                MessageBox.Show("The OCSP server reports that the certificate is valid!", "Result", MessageBoxButton.OK, MessageBoxImage.Information)
            Case OCSPQueryResponse.ClientUnknownException
                PresentationUtilities.ShowStandardMessage(StandardMessages.ClientUnknown)
            Case OCSPQueryResponse.SignatureException
                PresentationUtilities.ShowStandardMessage(StandardMessages.ClientSignatureInvalid)
        End Select
    End Sub

    Private Sub DownloadCRL_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Try
            Select Case CRLManager.DownloadCRL
                Case GenericQueryResponse.Ok
                    LoadCRLTab()
                Case GenericQueryResponse.ClientUnknownException
                    MessageBox.Show(Me, "Error! The CA reports that it doesn't know you yet. Please register to the CA by requesting a signature certificate before doing anything else.", "Client unknown", MessageBoxButton.OK, MessageBoxImage.Information)
                Case GenericQueryResponse.SignatureException
                    MessageBox.Show(Me, "Error! The CA reports that the signature verification failed! Something went horribly wrong :(", "Signature invalid", MessageBoxButton.OK, MessageBoxImage.Error)
            End Select
        Catch ex As SignatureException
            MessageBox.Show(Me, "Error! The CA reply to your query failed the signature verification. The CA has been compromised!", "Signature invalid", MessageBoxButton.OK, MessageBoxImage.Error)
        End Try
    End Sub
#End Region

    Private Sub TimerElapsed(sender As Object, e As Timers.ElapsedEventArgs)
        If Me.Dispatcher.Thread IsNot Thread.CurrentThread Then
            Me.Dispatcher.BeginInvoke(New TimerElapsedDelegate(AddressOf TimerElapsed), {sender, e})
            Return
        End If

        If Repository.CurrentProfile IsNot Nothing AndAlso Repository.CurrentProfile.LocalCRL IsNot Nothing Then
            LoadCRLTab()
        End If
        LoadCertsTab()
    End Sub
    Private Delegate Sub TimerElapsedDelegate(sender As Object, e As Timers.ElapsedEventArgs)

    Private Sub buttonLogout_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim res = MessageBox.Show("Are you sure you want to log out?", "Confirm logout", MessageBoxButton.YesNo, MessageBoxImage.Question)
        If res = MessageBoxResult.Yes Then
            Process.Start(Application.ResourceAssembly.Location)
            Application.Current.Shutdown()
        End If
    End Sub
End Class
